package com.corpgovernment.common.supplier;

import com.corpgovernment.common.utils.BaseUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 供应商token
 */
public class SupplierSign {
    /**
     * 获取token
     *
     * @param userKey
     * @param guid
     * @param time
     * @return
     */
    public static String createSign(String userKey, String guid, String time) {
        String formString = String.format("userkey=%s&guid=%s&time=%s", userKey, guid, time);
        return SHA256Utils.getSHA256StrJava(SHA256Utils.getSHA256StrJava(formString));
    }

    /**
     * 获取token
     *
     * @param userKey
     * @param guid
     * @return
     */
    public static String createSign(String userKey, String guid) {
        String formString = String.format("userkey=%s&guid=%s", userKey, guid);
        return MD5Util.md5(formString);
    }

    /**
     * 创建签名信息
     *
     * @param userKey
     * @return
     */
    public static Map<String, String> createSignInfo(String userKey) {
        Map<String, String> map = new HashMap<>(5);
        String guid = BaseUtils.getUUID();
        String time = BaseUtils.getTime().toString();

        map.put("id", String.format("%s%s", guid, time));
        map.put("token", createSign(userKey, guid, time));

        return map;
    }

    /**
     * 检查时间戳
     *
     * @param userKey
     * @param guid
     * @param time
     * @param checkSign
     * @return
     */
    public static boolean checkSign(String userKey, String guid, String time, String checkSign) {
        return createSign(userKey, guid, time).equals(checkSign);
    }

    /**
     * 检查时间戳
     *
     * @param userKey
     * @param idString
     * @param checkSign
     * @return
     */
    public static boolean checkSign(String userKey, String idString, String checkSign) {
        if (StringUtils.isBlank(idString)) {
            return false;
        }
        if (idString.length() < 36) {
            return false;
        }
        String guid = idString.substring(0, 36);
        String time = idString.substring(36);
        return checkSign(userKey, guid, time, checkSign);
    }


}
